package com.jyu.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jyu.reggie.common.R;
import com.jyu.reggie.dto.DishDto;
import com.jyu.reggie.entity.Category;
import com.jyu.reggie.entity.Dish;
import com.jyu.reggie.entity.DishFlavor;
import com.jyu.reggie.service.CategoryService;
import com.jyu.reggie.service.DishFlavorService;
import com.jyu.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * @description: 保存
     * @param dishDto
     * @return: com.jyu.reggie.common.R<java.lang.String>
     * @date: 2023/7/27 21:31
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.saveWithFlavor(dishDto);

        return R.success("新增菜品成功");
    }
    /**
     * @description: 分页查询
     * @param page
 * @param pageSize
 * @param name
     * @return: com.jyu.reggie.common.R<com.baomidou.mybatisplus.extension.plugins.pagination.Page>
     * @date: 2023/7/27 21:30
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){

        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();

        qw.like(name!= null,Dish::getName,name);

        qw.orderByDesc(Dish::getUpdateTime);

        dishService.page(pageInfo, qw);

        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = dishDto.getCategoryId();

            Category category = categoryService.getById(categoryId);

            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }

            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * @description:  回显数据
     * @param id
     * @return: com.jyu.reggie.common.R<com.jyu.reggie.dto.DishDto>
     * @date: 2023/7/27 21:44
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * @description: 修改
     * @param dishDto
     * @return: com.jyu.reggie.common.R<java.lang.String>
     * @date: 2023/7/27 21:31
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.updateWithFlavor(dishDto);

        //清理所有的缓存数据
//        Set keys = redisTemplate.keys("dish_");
//        //
//        String key = "dish_"+dishDto.getCategoryId()+"_1";
//        redisTemplate.delete(key);

        return R.success("新增菜品成功");
    }

    /**
     * @description: 根据条件查询菜品数据
     * @param dish
     * @return: com.jyu.reggie.common.R<java.util.List<com.jyu.reggie.entity.Dish>>
     * @date: 2023/7/27 22:16
     */
    @GetMapping("/list")
    public R<List<DishDto>> list( Dish dish){
        List<DishDto> dishDtos =null;

        String key = "dish_" + dish.getCategoryId() +"_" + dish.getStatus();
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if( dishDtos != null ){
            return R.success(dishDtos);
        }

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        dishDtos = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);

            if(category!= null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);

            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        redisTemplate.opsForValue().set(key,dishDtos,60, TimeUnit.MINUTES);

        return R.success(dishDtos);
    }

    /*@GetMapping("/list")
    public R<List<Dish>> list( Dish dish){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);

        return R.success(list);
    }*/

    @PostMapping("/status/{status}")
    public R<String> outOfStock( @PathVariable Integer status, Long [] ids ){
        System.out.println("==========================unsold==============================");
        for (Long  id : ids) {
            LambdaUpdateWrapper<Dish> updateWrapper = new LambdaUpdateWrapper<>();

            updateWrapper.eq(Dish::getId,id);

            updateWrapper.set(Dish::getStatus,status != 0 ? 1:0);

            dishService.update(updateWrapper);
        }
        return R.success("状态已变更");
    }

    /**
     * 批量删除 菜品  单珊，和 批量删统一方法
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(  Long [] ids){
        System.out.println("============delete==============");

        dishService.removeByIds(Arrays.asList(ids));

        return R.success("已删除");
    }
}

